<?php
use app\api\model\Integral;

/**
 * 友好的时间显示
 *
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime      =   time();
    $dTime      =   $cTime - $sTime;
    $dDay       =   intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear      =   intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            if($dTime < 10){
                return '刚刚';    //by yangjs
            }else{
                return intval(floor($dTime / 10) * 10)."秒前";
            }
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
    //full: Y-m-d , H:i:s
    }elseif($type=='full'){
        return date("Y-m-d , H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

/**
 * 根据用户的好评数和中评数计算信誉度
 * @param int $praise   好评数
 * @param int $commonly 中评数
 * @param int $negative_comment 差评数
 * @return \think\response\Json
 */
function praise($praise=0, $commonly=0, $negative_comment=0)
{
    $total = $praise + $commonly + $negative_comment;   //总评数
    $praise_total = $total - $negative_comment;   //好评+中评数总数

    if($praise_total == 0){
      return $menber = 0;
    } else{
      return $menber = intval(($praise + $commonly*(4/5))/$total*100);
    }
}


/**
 * 生成toekn
 * @param array $data
 * @param string $msg
 * @return \think\response\Json
 */
function genToken( $len = 50, $md5 = true ) {  
# Seed random number generator  
  # Only needed for PHP versions prior to 4.2  
  mt_srand( (double)microtime()*1000000 );  
  # Array of characters, adjust as desired  
  $chars = array(  
      'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',  
      'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',  
      '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',  
      'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',  
      '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',  
      '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',  
      'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'  
  );  
  # Array indice friendly number of chars;  
  $numChars = count($chars) - 1; $token = '';  
  # Create random token at the specified length  
  for ( $i=0; $i<$len; $i++ )  
      $token .= $chars[ mt_rand(0, $numChars) ];  
  # Should token be run through md5?  
  if ( $md5 ) {  
      # Number of 32 char chunks  
      $chunks = ceil( strlen($token) / 32 ); $md5token = '';  
      # Run each chunk through md5  
      for ( $i=1; $i<=$chunks; $i++ )  
          $md5token .= md5( substr($token, $i * 32 - 32, 32) );  
      # Trim the token  
      $token = substr($md5token, 0, $len);  
  } 

  return $token;  
} 

/**
 * 返回成功
 * @param array $data
 * @param string $msg
 * @return \think\response\Json
 */
function success($data = [], $msg = '')
{
    $response = array(
        'code' => 0,
        'message' => $msg,
        'data' => $data,
    );
    return json($response, 200, ['Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
        'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,DELETE']);
}

/**
 * 返回失败
 * @param string $msg
 * @param array $data
 * @return \think\response\Json
 */
function error($msg = '', $data = [])
{
    $response = array(
        'code' => 1,
        'message' => $msg,
        'data' => $data,
    );
    return json($response, 200, ['Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
        'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,DELETE']);
}

/**
 * 分页格式化
 * @param string $name 数据名
 * @param array|\think\Paginator $pageData
 * @return array
 */
function formatPage($name, $pageData)
{
    if (!is_array($pageData)) {
        $pageData = $pageData->toArray();
    }
    $pages = $pageData['last_page'];
    $data = $pageData['data'];
    return [$name => $data, 'pages' => $pages];
}

/*
 *  积分入库管理
 *  $channel 来源渠道|1：登录， 2:注册, 3：发布文章，4：交易成功赠送 5:邀请注册 6：消费积分
 *  $type 类型|1：增加，2：减少
 *  $menber 数量
 */
function add_signin($channel, $type, $menber, $user_id, $content)
{
    $res = Integral::create([
        'user_id' => $user_id,
        'channel' => $channel,
        'type' => $type,
        'menber' => $menber,
        'content' => $content,
        'create_at' => time(),
    ]);

    return $res;
}

/*
 *  预算价格
 *  @param float $price 交易金额
 *  @param int $type 1,买家支付 2,卖家支付 3,双方均摊 4,双向收费（新媒体）
 *
 *  @return array
 *  buyer_price 买家需付金额
 *  seller_price 卖家实收金额
 */
function price_budget($price,$type){
    //设置收费比例
    $proportion = 0.03;

    if($type == 1){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price;
    }elseif ($type == 2){
        $data['buyer_price'] = $price;
        $data['seller_price'] = $price * (1 - $proportion);
    }elseif($type == 3){
        $data['buyer_price'] = $price * (1 + $proportion/2);
        $data['seller_price'] = $price * (1 - $proportion/2);
    }elseif($type == 4){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price * (1 - $proportion);
    }else{
        return false;
    }

    return $data;
}

/**
 * 生成唯一的订单编号
 * @return string
 */
function get_order_num()
{
    @date_default_timezone_set("PRC");
    $order_date = date('Y-m-d');
    $order_id_main = date('YmdHis') . rand(10, 99);
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    return $order_id;
}